class ChatApp {
    constructor() {
        this.chatMessages = document.getElementById('chatMessages');
        this.userInput = document.getElementById('userInput');
        this.sendButton = document.getElementById('sendButton');
        this.isProcessing = false; // 添加处理状态标志

        // 确保 marked 和 hljs 已加载
        if (typeof marked === 'undefined' || typeof hljs === 'undefined') {
            console.error('marked 或 highlight.js 未加载');
            return;
        }

        // 配置 marked 选项
        marked.setOptions({
            renderer: new marked.Renderer(),
            highlight: function(code, language) {
                if (language && hljs.getLanguage(language)) {
                    try {
                        return hljs.highlight(code, { language }).value;
                    } catch (err) {
                        console.error('代码高亮错误:', err);
                    }
                }
                return code;
            },
            pedantic: false,
            gfm: true,
            breaks: true,
            sanitize: false,
            smartypants: false,
            xhtml: false
        });

        // 绑定事件
        this.sendButton.addEventListener('click', () => {
            if (!this.isProcessing) {
                this.sendMessage();
            }
        });
        this.userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !this.isProcessing) {
                this.sendMessage();
            }
        });

        // 添加调试日志
        console.log('ChatApp 初始化完成');
    }

    createMessageContainer(message, type) {
        const container = document.createElement('div');
        container.classList.add('message-container');

        // 创建消息头部（包含头像和名称）
        const header = document.createElement('div');
        header.classList.add('message-header');

        const avatar = document.createElement('div');
        avatar.classList.add('avatar', `${type}-avatar`);
        avatar.textContent = type === 'user' ? '用' : 'AI';

        const name = document.createElement('span');
        name.textContent = type === 'user' ? '用户' : 'AI助手';

        header.appendChild(avatar);
        header.appendChild(name);
        container.appendChild(header);

        // 创建消息内容
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', `${type}-message`);
        if (type === 'user') {
            messageDiv.textContent = message;
        } else {
            messageDiv.innerHTML = marked.parse(message);
            messageDiv.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
            });
        }
        container.appendChild(messageDiv);

        return container;
    }

    createThinkingMessage() {
        const container = document.createElement('div');
        container.classList.add('message-container', 'thinking-container');

        const header = document.createElement('div');
        header.classList.add('message-header');

        const avatar = document.createElement('div');
        avatar.classList.add('avatar', 'ai-avatar');
        avatar.textContent = 'AI';

        const name = document.createElement('span');
        name.textContent = 'AI助手';

        header.appendChild(avatar);
        header.appendChild(name);
        container.appendChild(header);

        const thinking = document.createElement('div');
        thinking.classList.add('message', 'ai-message', 'thinking');
        thinking.innerHTML = `
            <span>思考中</span>
            <div class="thinking-dots">
                <div class="thinking-dot"></div>
                <div class="thinking-dot"></div>
                <div class="thinking-dot"></div>
            </div>
        `;
        container.appendChild(thinking);

        return container;
    }

    async sendMessage() {
        const message = this.userInput.value.trim();
        if (!message) return;

        // 设置处理状态
        this.isProcessing = true;
        this.sendButton.disabled = true;
        this.sendButton.style.opacity = '0.6';
        this.sendButton.style.cursor = 'not-allowed';
        this.userInput.disabled = true;

        // 添加用户消息
        const userMessageContainer = this.createMessageContainer(message, 'user');
        this.chatMessages.appendChild(userMessageContainer);
        this.userInput.value = '';

        // 添加思考动画
        const thinkingContainer = this.createThinkingMessage();
        this.chatMessages.appendChild(thinkingContainer);
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;

        try {
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'text/event-stream',
                },
                body: JSON.stringify({ message: message })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 移除思考动画
            this.chatMessages.removeChild(thinkingContainer);

            // 创建 AI 回复容器
            const aiMessageContainer = this.createMessageContainer('', 'ai');
            const aiMessageDiv = aiMessageContainer.querySelector('.ai-message');
            this.chatMessages.appendChild(aiMessageContainer);

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let markdown = '';

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n');

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        try {
                            const data = JSON.parse(line.slice(6));
                            markdown += data.content;
                            aiMessageDiv.innerHTML = marked.parse(markdown);
                            aiMessageDiv.querySelectorAll('pre code').forEach((block) => {
                                hljs.highlightElement(block);
                            });
                            this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
                        } catch (e) {
                            console.error('解析响应数据错误:', e);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('API 调用错误:', error);
            // 移除思考动画
            this.chatMessages.removeChild(thinkingContainer);
            // 添加错误消息
            const errorContainer = this.createMessageContainer('抱歉，发生了一些错误，请稍后重试。', 'ai');
            this.chatMessages.appendChild(errorContainer);
        } finally {
            // 恢复发送按钮和输入框状态
            this.isProcessing = false;
            this.sendButton.disabled = false;
            this.sendButton.style.opacity = '1';
            this.sendButton.style.cursor = 'pointer';
            this.userInput.disabled = false;
            this.userInput.focus();
        }

        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }
}

// 等待 DOM 和所有脚本加载完成
window.addEventListener('load', () => {
    try {
        new ChatApp();
    } catch (e) {
        console.error('ChatApp 初始化错误:', e);
    }
});